package com.pride1952.myoptimusx3;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WebActivity extends Activity {

    private static final String TAG = "WebActivity";
    private WebView webView;
    public static BluetoothLeService mBluetoothLeService;
    private String webUrl;
    private ProgressBar progressBarTitle;
    private RelativeLayout layoutCover;
    private Button webTitleBack;
    private Button webTitleMenu;
    private TextView mTxtCover;
    private CookieManager cookieManager = CookieManager.getInstance();

    private IntentFilter intentFilter(){
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_NEAR);
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_NOT_NEAR);
        return intentFilter;
    }
    private BroadcastReceiver bcReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action)
            {
                case BluetoothLeService.mACTION_DEVICE_NEAR:
                    cookieManager.setAcceptCookie(true); //设置是否使用cookie
                    webView.loadUrl(webUrl);
                    layoutCover.setVisibility(View.GONE);
                    break;
                case BluetoothLeService.mACTION_DEVICE_NOT_NEAR:
                    //弹出重试界面
                    mTxtCover.setText("连接超时\n点击重试");
                    layoutCover.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mTxtCover.setText("请把手环\n靠近手机");
                            if (mBluetoothLeService.isReady()) {
                                mBluetoothLeService.doJudgeDeviceNear();
                            } else {
                                //换界面
                                mTxtCover.setText("手环未就绪");
                            }
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };
//    public PopupWindow initPopShow(int imageId,String text,boolean isTouchable)
//    {
//        View view2 = getLayoutInflater().inflate(R.layout.popupwindow_show, null);
//        PopupWindow pop = new PopupWindow(view2, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        pop.showAtLocation(findViewById(R.id.web_cover), Gravity.CENTER_HORIZONTAL, 0, 0);
//        pop.setOutsideTouchable(true);
//        if(isTouchable) {
//            TextView txtTip=(TextView)view2.findViewById(R.id.txt_pop_show_tip);
//            txtTip.setVisibility(View.VISIBLE);
//            final PopupWindow finalPop = pop;
//            view2.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    finalPop.dismiss();
//                }
//            });
//        }
//        ImageView img=(ImageView)view2.findViewById(R.id.img_pop_show);
//        img.setBackgroundResource(imageId);
//        TextView txt=(TextView)view2.findViewById(R.id.txt_pop_show);
//        txt.setText(text);
//        return pop;
//    }

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            Log.i(TAG, "onServiceConnected called.");
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if(mBluetoothLeService.isReady()){
                mBluetoothLeService.doJudgeDeviceNear();
            }
            else{
                //换界面
                mTxtCover.setText("手环未就绪");
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Toast.makeText(getApplicationContext(),"连接中断",Toast.LENGTH_SHORT).show();
            Log.e(TAG,"Disconnected");
            mBluetoothLeService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        registerReceiver(bcReceiver, intentFilter());

        layoutCover=(RelativeLayout)findViewById(R.id.web_cover);
        mTxtCover=(TextView)findViewById(R.id.cover_waiting);

        webTitleBack = (Button) findViewById(R.id.webtitle_back);
        webTitleMenu = (Button) findViewById(R.id.webtitle_menu);
		progressBarTitle = (ProgressBar) findViewById(R.id.webtitle_progressbar);
        webTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
		});
		webTitleMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cookieManager.removeSessionCookie();
                Toast.makeText(WebActivity.this, "注销成功", Toast.LENGTH_SHORT).show();
                webView.loadUrl(webUrl);
            }
        });

        webView = (WebView) findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);	//允许JavaScript
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setSupportZoom(true);          //允许缩放
        webView.getSettings().setBuiltInZoomControls(true);  //原网页基础上缩放
        webView.getSettings().setUseWideViewPort(true);     //任意比例缩放
        webView.requestFocus();        //获取焦点

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {    //点击请求为连接时调用
                view.loadUrl(url); // 根据传入的参数再去加载新的网页
                return true; // 表示当前WebView可以处理打开新网页的请求，不用借助系统浏览器
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBarTitle.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView webView, String url) {
                progressBarTitle.setVisibility(View.GONE);
                Log.d(TAG, "onPageFinished: " + webView.getUrl());
            }

            //设置处理https
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                handler.cancel();
                handler.handleMessage(null);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int newProgress) {
                progressBarTitle.setProgress(newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                TextView webTitle = (TextView) findViewById(R.id.webtitle_text);
                webTitle.setText(title);
            }
        });
        judgWebsite();
        cookieManager.setAcceptCookie(false); //设置是否使用cookie
        webView.loadUrl(webUrl);

        //yinchao   设置无手环模式按钮
        Button mBtnTypeIn = (Button)findViewById(R.id.cover_btn_typein);
        mBtnTypeIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadWithoutRing();
            }
        });
/*        //临时进入按钮
        Button mBtnTmp = (Button) findViewById(R.id.cover_btn_tmp);
        mBtnTmp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutCover.setVisibility(View.GONE);
            }
        });*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        unregisterReceiver(bcReceiver);
    }

    //返回上一页而不是finish()
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && (event.getKeyCode() == KeyEvent.KEYCODE_BACK) && event.getRepeatCount() == 0) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 调用该方法根据intent参数判决webUrl值，并采取相应的操作
     * 注意需在webView初始化后再调用
     * */
    private void judgWebsite(){
        String webTitle = getIntent().getStringExtra("webTitle");
        Log.d(TAG, "judgWebsite webTitle= " + webTitle);
        webUrl = webSite.getSite(webTitle);
        if(webUrl.equals(webSite.getSite("北航教务"))){
            webTitleMenu.setVisibility(View.VISIBLE);
        }
        Log.d(TAG,"normal webUrl: " + webUrl);
    }

    /**
     * 调用该方法实现无手环登录
     * 跳至外部浏览器
     * */
    private void loadWithoutRing(){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(webUrl));
        startActivity(intent);
    }

}

